<?php

declare(strict_types=1);

namespace app\controller\system\region;

use app\BaseController;
use app\model\RegionUser as RegionUserModel;
use app\service\factory\ResponseFactory;
use app\service\region\RegionUserService;
use app\validate\region\RegionUserValidate;
use InvalidArgumentException;
use think\Response;
use Throwable;

class User extends BaseController
{
    public function index(RegionUserService $regionUserService): Response
    {
        try {
            $page = max(1, (int) $this->request->param('page', 1));
            $pageSize = (int) $this->request->param('page_size', 20);
            $pageSize = $pageSize > 0 ? min($pageSize, 100) : 20;

            $filters = $this->request->only([
                'region_id',
                'user_id',
                'role_type',
                'status',
            ], 'get');

            $paginator = $regionUserService->paginate($filters, $page, $pageSize);

            $list = array_map(
                static fn(RegionUserModel $relation) => $regionUserService->format($relation),
                $paginator->items()
            );

            return json(ResponseFactory::paginated(
                $list,
                (int) $paginator->total(),
                $page,
                $pageSize
            ));
        } catch (Throwable $e) {
            return json(ResponseFactory::error($e->getMessage(), $e->getCode() ?: 500));
        }
    }

    public function read(int $id, RegionUserService $regionUserService): Response
    {
        try {
            $relation = $regionUserService->findById($id);
            if (!$relation) {
                return json(ResponseFactory::error('区域成员不存在', 404));
            }

            return json(ResponseFactory::success($regionUserService->format($relation)));
        } catch (Throwable $e) {
            return json(ResponseFactory::error($e->getMessage(), $e->getCode() ?: 500));
        }
    }

    public function save(RegionUserService $regionUserService): Response
    {
        try {
            $payload = $this->request->post();

            $this->validate($payload, RegionUserValidate::class . '.create');

            $relation = $regionUserService->create($payload);

            return json(ResponseFactory::success($regionUserService->format($relation), '区域成员已添加'));
        } catch (InvalidArgumentException $e) {
            return json(ResponseFactory::error($e->getMessage(), 422));
        } catch (Throwable $e) {
            return json(ResponseFactory::error($e->getMessage(), $e->getCode() ?: 500));
        }
    }

    public function update(int $id, RegionUserService $regionUserService): Response
    {
        try {
            $relation = RegionUserModel::find($id);
            if (!$relation) {
                return json(ResponseFactory::error('区域成员不存在', 404));
            }

            $payload = $this->request->put();
            $payload['id'] = $id;

            $this->validate($payload, RegionUserValidate::class . '.update');

            $updated = $regionUserService->update($relation, $payload);

            return json(ResponseFactory::success($regionUserService->format($updated), '区域成员已更新'));
        } catch (InvalidArgumentException $e) {
            return json(ResponseFactory::error($e->getMessage(), 422));
        } catch (Throwable $e) {
            return json(ResponseFactory::error($e->getMessage(), $e->getCode() ?: 500));
        }
    }

    public function delete(int $id, RegionUserService $regionUserService): Response
    {
        try {
            $relation = RegionUserModel::find($id);
            if (!$relation) {
                return json(ResponseFactory::error('区域成员不存在', 404));
            }

            if (!$regionUserService->delete($relation)) {
                return json(ResponseFactory::error('删除失败', 500));
            }

            return json(ResponseFactory::success(true, '区域成员已删除'));
        } catch (InvalidArgumentException $e) {
            return json(ResponseFactory::error($e->getMessage(), 422));
        } catch (Throwable $e) {
            return json(ResponseFactory::error($e->getMessage(), $e->getCode() ?: 500));
        }
    }
}
